package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;

/**
 * Created by zhour on 2016/11/23.
 */
//@Configuration
//@EnableTransactionManagement
//@MapperScan("com.ge.mapper")
public class DatabaseConfiguration implements EnvironmentAware {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class);
    private Environment environment;
    private DataBaseProperty dataBaseProperty;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
        dataBaseProperty = Binder.get(environment)
                                    .bind("spring.datasource",DataBaseProperty.class)
                                    .orElse(null);
        System.out.println(1234);
    }
    //注册dataSource
    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();

        if (StringUtils.isEmpty(dataBaseProperty.getUrl())) {
            throw new ApplicationContextException(
                    "Database connection pool is not configured correctly");
        }
        druidDataSource.setDriverClassName(dataBaseProperty.getDriverClassName());
        druidDataSource.setUrl(dataBaseProperty.getUrl());
        druidDataSource.setUsername(dataBaseProperty.getUsername());
        druidDataSource.setPassword(dataBaseProperty.getPassword());
        druidDataSource.setInitialSize(Integer.parseInt(dataBaseProperty.getInitialSize()));
        druidDataSource.setMinIdle(Integer.parseInt(dataBaseProperty.getMinIdle()));
        druidDataSource.setMaxActive(Integer.parseInt(dataBaseProperty.getMaxActive()));
        druidDataSource.setMaxWait(Integer.parseInt(dataBaseProperty.getMaxWait()));
        druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(dataBaseProperty.getTimeBetweenEvictionRunsMillis()));
        druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(dataBaseProperty.getMinEvictableIdleTimeMillis()));
        druidDataSource.setValidationQuery(dataBaseProperty.getValidationQuery());
        druidDataSource.setTestWhileIdle(Boolean.parseBoolean(dataBaseProperty.getTestWhileIdle()));
        druidDataSource.setTestOnBorrow(Boolean.parseBoolean(dataBaseProperty.getTestOnBorrow()));
        druidDataSource.setTestOnReturn(Boolean.parseBoolean(dataBaseProperty.getTestOnReturn()));
        druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(dataBaseProperty.getPoolPreparedStatements()));
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(dataBaseProperty.getMaxPoolPreparedStatementPerConnectionSize()));
        druidDataSource.setFilters(dataBaseProperty.getFilters());
        return druidDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(
                resolver.getResources("classpath:mybatis/**/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }
    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }
}
